package net.oschina.app.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by YL on 2017/4/1.
 */

public class URLGet<T> {
    private Class<T> clzz;

    public void getData(final String path, final Class<T> clzz, final OnURLGetLitener onURLGetLitener) {
        this.clzz = clzz;
        String key = Md5Utils.md5(path);
        String result = MApp.mCacheUtils.getCache(key);
        if (result == null || TextUtils.isEmpty(result)) {// 去网络加载数据
            TLog.log("从网络中加载数据");
            loadNetData(UIUtils.getContext(), path, onURLGetLitener);
        } else {
            TLog.log("从缓存中加载数据");
            T bean = XmlUtils.toBean(clzz, result.getBytes());
            if (onURLGetLitener != null) {
                onURLGetLitener.showSuccess(bean);
            }
        }

    }


    private void loadNetData(Context context, final String path, final OnURLGetLitener onURLGetLitener) {
        // 1 通过url 获取 okhttp 的call
        Call call = getCall(path);
        // 2 执行异步的操作
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (onURLGetLitener != null) {
                    onURLGetLitener.showError(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                T bean = XmlUtils.toBean(clzz, result.getBytes());
                String key = Md5Utils.md5(path);
                //缓存
                // PreferencesUtils.putString(UIUtils.getContext(), key, result);
                //三级缓存存储数据到内存，磁盘
                MApp.mCacheUtils.savecache(key, result);
                Log.d("xxx", "finish");
                //回调结果
                onURLGetLitener.showSuccess(bean);
            }
        });

    }

    // 通过url 获取 okhttp 的call
    private Call getCall(String url) {
        // 2 构建Request
        Request.Builder builder = new Request.Builder().url(url);
        Request request = builder.build();
        //3.通过request构建call
        return MApp.mClient.newCall(request);
    }

    public interface OnURLGetLitener<T> {
        void showSuccess(T bean);

        void showError(Exception e);
    }
}
